package com.xbdun.web.bmp.controller.system;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xbdun.common.api.XbdUnStringResult;
import com.xbdun.common.constant.XbdunLoginConst;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.comweb.bmp.frame.annotation.XbdunLogin;
import com.xbdun.comweb.bmp.util.UserInfoUtil;
import com.xbdun.facade.bmp.constant.DubboBmpConst;
import com.xbdun.facade.bmp.request.system.ModifyOrgUserRequest;
import com.xbdun.facade.bmp.request.system.ModifyUserPowerRequest;
import com.xbdun.facade.bmp.request.system.OrgUserPagerRequest;
import com.xbdun.facade.bmp.request.system.OrgUserPowerMenuRequest;
import com.xbdun.facade.bmp.request.system.OrgUserRequest;
import com.xbdun.facade.bmp.request.system.UserSpecialPowerRequest;
import com.xbdun.facade.bmp.result.system.OrgUserPagerResult;
import com.xbdun.facade.bmp.result.system.OrgUserPowerMenuResult;
import com.xbdun.facade.bmp.result.system.OrgUserResult;
import com.xbdun.facade.bmp.service.system.OrgUserFacade;
import com.xbdun.facade.validatebmp.constant.DubboValidateBmpConst;
import com.xbdun.facade.validatebmp.menus.UploadFileFormat;
import com.xbdun.facade.validatebmp.request.OpenUploadReqeust;
import com.xbdun.facade.validatebmp.service.upload.OpenUploadFacade;
import com.xbdun.web.bmp.request.ModUserPowerRequest;
import com.xbdun.web.bmp.request.ModUserSpePowerRequest;
import com.xbdun.web.bmp.service.EmailNotifyService;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: S103103Controller
 * @Description: 企业员工信息
 * @author wwq
 * @date 2017年5月3日13:28:03
 */
@Controller
@Slf4j
@XbdunLogin({XbdunLoginConst.XBDADMINT,XbdunLoginConst.ADMINS})
public class S100101103Controller extends BaseSystemController{
	@Reference(registry=DubboBmpConst.REGISTRYS)
	OrgUserFacade orgUserFacade;
	@Autowired
	EmailNotifyService emailNotifyService;
	@Reference(registry=DubboValidateBmpConst.REGISTRYS)
	OpenUploadFacade openUploadFacade;
	
	@RequestMapping("100101103")
    public String index(){
		return ROOT_PATH+"100101103";	
	}
	/**
	 * 检索企业员工信息
	 */
	@RequestMapping("100101103103")
	@ResponseBody
	public OrgUserPagerResult queryOrgUserPager(OrgUserPagerRequest request){
		OrgUserPagerResult result = new OrgUserPagerResult();
		try{
			log.info("检索企业员工信息传入参数{}",request);
			result = orgUserFacade.queryOrgUserPager(request, UserInfoUtil.getClient(getRequest()));
		}catch(Exception e){
			result.setBizException(e);
			log.error("检索企业员工信息异常,{}", e);
		}
		return result;
	}
	
	/***
	 * 新增企业员工信息
	 */
	@RequestMapping("100101103100")
	@ResponseBody
	public XbdUnStringResult addOrgUser(OrgUserRequest request){
		XbdUnStringResult result = new XbdUnStringResult();
		try{
			log.info("新增企业员工信息传入参数,{}", request);
			result = orgUserFacade.addOrgUser(request, UserInfoUtil.getClient(getRequest()));
			//新增企业员工成功
			if(result.getSuccess()){
				//邮件邀请且启用
				if(3==request.getInvitType()&&request.getEnabled()==1){
					emailNotifyService.sendAddOrgUser(getRequest(),request);
				}
			}
		}catch(Exception e){
			result.setBizException(e);
			log.error("新增企业员工信息异常,{}", e);
		}
		return result;
	}
	
	/**
	 * @Title getUserImgUrl
	 * @Description 获取用户头像
	 * @return XbdUnStringResult 返回值类型
	 */
	@RequestMapping("100101103100X")
	@ResponseBody
	public XbdUnStringResult getUserImgUrl(String imgId){
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("获取用户头像请求参数：{}"+imgId);
			if(StringUtils.isNotBlank(imgId)){
				OpenUploadReqeust request = new OpenUploadReqeust();
				request.setFiledId(new long[]{NumberUtils.toLong(imgId)});
				request.setOrgCode(UserInfoUtil.getClient(getRequest()).getOrgCode());
				request.setUploadFormat(UploadFileFormat.USER_MAX.name());
				result.setData(openUploadFacade.getUrl(request).getData());
			}
		} catch (Exception e) {
			log.error("获取用户头像失败：{}"+e);
			result.setBizException(e);
		}
		return result;
	}
	
	/**
	 * 修改企业员工信息
	 */
	@RequestMapping("100101103101")
	@ResponseBody
	public XbdUnStringResult modifyOrgUser(ModifyOrgUserRequest request){
		XbdUnStringResult result = new XbdUnStringResult();
		try{
			log.info("修改企业员工传入参数,{}",request);
			result = orgUserFacade.modifyOrgUser(request, UserInfoUtil.getClient(getRequest()));
		}catch(Exception e){
			result.setBizException(e);
			log.error("修改企业员工异常,{}", e);
		}
		return result;
	}
	/**
	 * 修改企业员工邀请方式
	 */
	@RequestMapping("100101103101X")
	@ResponseBody
	public XbdUnStringResult inviteOrgUser(String userId,int inviteType,String realName,String orgEmail){
		XbdUnStringResult result = new XbdUnStringResult();
		try{
			log.info("修改企业员工邀请方式传入参数,{}");
			result = orgUserFacade.inviteOrgUser(userId,inviteType, UserInfoUtil.getClient(getRequest()));
			if(result.getSuccess()){
				//邮件邀请且启用
				if(3==inviteType){
					OrgUserRequest request = new OrgUserRequest();
					request.setRealName(realName);
					request.setOrgEmail(orgEmail);
					emailNotifyService.sendAddOrgUser(getRequest(),request);
				}
			}
		}catch(Exception e){
			result.setBizException(e);
			log.error("修改企业员工异常,{}", e);
		}
		return result;
	}
	
	/**
	 * 删除企业员工信息
	 */
	@RequestMapping("100101103102")
	@ResponseBody
	public XbdUnStringResult deleteOrgUser(String userId){
		XbdUnStringResult result = new XbdUnStringResult();
		try{
			log.info("删除企业员工传入参数,{}");
			result = orgUserFacade.deleteOrgUser(userId, UserInfoUtil.getClient(getRequest()));
		}catch(Exception e){
			result.setBizException(e);
			log.error("删除企业员工异常,{}", e);
		}
		return result;
	}
	
	/**
	 * 查询机构用户详情
	 */
	@RequestMapping("100101103104")
	@ResponseBody
	public OrgUserResult getOrgUserInfo(String userId){
		OrgUserResult result = new OrgUserResult();
		try{
			log.info("查询机构用户详情传入参数,{}");
			result = orgUserFacade.getOrgUserInfo(userId, UserInfoUtil.getClient(getRequest()));
			if(result.getSuccess()&&result.getData()!=null){
				String img = result.getData().getImgUrl();
				if(StringUtils.isNotBlank(img)){
					OpenUploadReqeust request = new OpenUploadReqeust();
					request.setFiledId(new long[]{Long.parseLong(img)});
					request.setOrgCode(UserInfoUtil.getClient(getRequest()).getOrgCode());
					request.setUploadFormat(UploadFileFormat.USER_MAX.name());
					result.getData().setImgRealUrl(openUploadFacade.getUrl(request).getData());
				}
			}
		}catch(Exception e){
			result.setBizException(e);
			log.error("查询机构用户详情异常,{}", e);
		}
		return result;
	}
	
	/**
	 * 给员工设置部门和角色权限
	 * @param webRequest
	 * @return
	 */
	@RequestMapping("100101103105")
	@ResponseBody
	public XbdUnStringResult addUserPower(ModUserPowerRequest webRequest){
		XbdUnStringResult result = new XbdUnStringResult();
		ModifyUserPowerRequest request = new ModifyUserPowerRequest();
		try{
			log.info("给员工设置部门和角色权限传入参数,{}");
			if (webRequest.getUserId()!=null){
				request.setUserId(webRequest.getUserId());
			}
			if (webRequest.getDepartCode() != null) {
				request.setDepartCode(webRequest.getDepartCode());
			}
			
			// 增加部门员工角色权限
			if (StringUtils.isNotBlank(webRequest.getAddRdpIdsStr())){
				String[] addRdpIdArr = webRequest.getAddRdpIdsStr().split(",");
				Set<Long> addRdpIds = new HashSet<Long>();
				for (int i = 0; i < addRdpIdArr.length; i ++){
					if (StringUtils.isNumeric(addRdpIdArr[i])) {
						addRdpIds.add(Long.valueOf(addRdpIdArr[i]));
					}
				}
				request.setRdpIds(addRdpIds);
				result = orgUserFacade.addUserDptRolePower(request, UserInfoUtil.getClient(getRequest()));
			}
			
			// 删除部门员工角色权限
			if (StringUtils.isNotBlank(webRequest.getDelRdpIdsStr())){
				String[] delRdpIdArr = webRequest.getDelRdpIdsStr().split(",");
				Set<Long> delRdpIds = new HashSet<Long>();
				for (int i = 0; i < delRdpIdArr.length; i ++){
					if (StringUtils.isNumeric(delRdpIdArr[i])) {
						delRdpIds.add(Long.valueOf(delRdpIdArr[i]));
					}
				}
				request.setRdpIds(delRdpIds);
				result = orgUserFacade.delUserDptRolePower(request, UserInfoUtil.getClient(getRequest()));
			}
		}catch(Exception e){
			result.setBizException(e);
			log.error("给员工设置部门和角色权限异常,{}", e);
		}
		return result;
	}
	
	/**
	 * 查询当前员工拥有的部门权限
	 * @param userId
	 * @return
	 */
	@RequestMapping("100101103105X")
	@ResponseBody
	public OrgUserPowerMenuResult queryOrgUserPower(OrgUserPowerMenuRequest request){
		OrgUserPowerMenuResult result = new OrgUserPowerMenuResult();
		try{
			log.info("查询当前员工拥有的部门权限传入参数,{}",request);
			result = orgUserFacade.queryOrgUserPower(request, UserInfoUtil.getClient(getRequest()));
		}catch(Exception e){
			result.setBizException(e);
			log.error("查询当前员工拥有的部门权限异常,{}", e);
		}
		return result;
	}
	
	/**
	 * 查询当前员工拥有的所有权限
	 * @param request
	 * @return
	 */
	@RequestMapping("100101103106X")
	@ResponseBody
	public OrgUserPowerMenuResult queryOrgUserAllPower(OrgUserPowerMenuRequest request){
		OrgUserPowerMenuResult result = new OrgUserPowerMenuResult();
		try{
			log.info("查询当前员工拥有的所有权限传入参数,{}",request);
			result = orgUserFacade.queryOrgUserPower(request, UserInfoUtil.getClient(getRequest()));
		}catch(Exception e){
			result.setBizException(e);
			log.error("查询当前员工拥有的所有权限异常,{}", e);
		}
		return result;
	}
	
	/**
	 * 设置当前员工特殊权限
	 * @param webRequest
	 * @return
	 */
	@RequestMapping("100101103106")
	@ResponseBody
	public XbdUnStringResult ModifyUserSpecialPower(ModUserSpePowerRequest webRequest){
		XbdUnStringResult result = new XbdUnStringResult();
		UserSpecialPowerRequest request = new UserSpecialPowerRequest();
		try{
			log.info("设置当前员工特殊权限传入参数,{}",webRequest);
			if (webRequest.getUserId() != null) {
				request.setUserId(webRequest.getUserId());
			}
			if (StringUtils.isNotBlank(webRequest.getAddPowersStr())){
				String[] addPowerArr = webRequest.getAddPowersStr().split(",");
				Set<Long> addPowers = new HashSet<Long>();
				for (int i = 0; i < addPowerArr.length; i ++){
					if (StringUtils.isNumeric(addPowerArr[i])) {
						addPowers.add(Long.valueOf(addPowerArr[i]));
					}
				}
				request.setAddPowers(addPowers);
			}
			if (StringUtils.isNotBlank(webRequest.getDelPowersStr())){
				String[] delPowerArr = webRequest.getDelPowersStr().split(",");
				Set<Long> delPowers = new HashSet<Long>();
				for (int i = 0; i < delPowerArr.length; i ++){
					if (StringUtils.isNumeric(delPowerArr[i])) {
						delPowers.add(Long.valueOf(delPowerArr[i]));
					}
				}
				request.setDelPowers(delPowers);
			}
			
			if (CollectionUtils.isNotEmpty(request.getAddPowers()) || CollectionUtils.isNotEmpty(request.getDelPowers())){
				result = orgUserFacade.modifyUserSpecialPower(request, UserInfoUtil.getClient(getRequest()));
			} else {
				throw BizException.PARAM_CHKE_FAIL.newInstance("未进行任何修改!");
			}
		}catch(Exception e){
			result.setBizException(e);
			log.error("设置当前员工特殊权限异常,{}", e);
		}
		return result;
	}
	
}